package com.keeley.spider.server;

import com.keeley.spider.ext.Client;
import com.keeley.spider.model.Apk;
import com.keeley.spider.util.ApkUtil;
import com.qixin.appmarket.apktools.ApkTools;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: Tianjun
 * Date: 14-9-25
 * Time: 下午4:03
 * To change this template use File | Settings | File Templates.
 */
public abstract class SpiderServer {
    public Logger logger = Logger.getLogger(Client.class);
    public Logger nameLog = Logger.getLogger(SpiderServer.class);

    protected String name;  //处理的名称
    protected String apkName;  //处理的文件名称

    public void setApkName(String apkName) {
        this.apkName = apkName;
    }

    protected SpiderServer(String name) {
        this.name = name;
    }

    /**
     * 得到文件下载地址
     * @return
     */
    public abstract String getDownUrl();

    /**
     * 文件下载目录
     * @return
     */
    public String getDownDir() {
        String date=new SimpleDateFormat("yyyyMMdd").format(new Date());
        return "F:\\temp\\"+name+"\\"+date;
    }

    /**
     * 下载文件
     * @param url
     * @return  本地文件路径
     */
    public String DownApk(String url){
        try {
            logger.info("准备下载到本地:"+url);
            String date=new SimpleDateFormat("yyyyMMdd").format(new Date());
            File file = new File(getDownDir(),apkName+".apk");
            FileUtils.copyURLToFile(new URL(url), file);
            logger.info(apkName+"下载完毕");
            return file.getAbsolutePath();
        } catch (IOException e) {
            logger.error(e);
            throw  new RuntimeException(apkName+"下载失败");
        }
    }

    /**
     * 判断更新
     */
    public boolean checkUpdate(String localUrl){
        //step1:获取签名
        String signature = null;
        Map<String, String> apkInfo = null;
        try {
            signature = ApkTools.getSignatureAsMd5String(localUrl);
            apkInfo = ApkUtil.getApkInfo(localUrl);
        } catch (Exception e) {
            logger.error(e);
            throw  new RuntimeException(apkName+"签名解析失败");
        }
        logger.info("远程版本:"+(apkInfo.get("versionCode")) + "|" + (apkInfo.get("name")) + "|" + (apkInfo.get("versionName")));

        Apk oldApk=Apk.dao.getApk(signature,apkInfo.get("name"),apkInfo.get("versionCode"));
        if(oldApk!=null){
             nameLog.info(name+":"+apkName+"|需要更新:本地版本:"+oldApk.getStr("package_version_code")+"|"+oldApk.getStr("package_version"));
             return true;
        }else{
            logger.info(name+":"+apkName+"|不需要更新");
            return false;
        }

    }

}
